package offline;

import java.util.Random;

import tlsb.Utils;
import util.IFileWriter;
import util.IPartition;
import util.RedisCluster;

public class CommunityGen {
	RedisCluster cluster;
	IFileWriter ifr;
	IPartition sPart;
	Random random = new Random();

	public CommunityGen(RedisCluster cluster_, IFileWriter ifr_) {
		ifr = ifr_;
		cluster = cluster_;
		sPart = cluster.getPartition();
	}

	public String getFirstCommunity(String uid) {
		String cid = cluster.getJedis(sPart.shard(uid)).hget(uid,
				CGAXiafan.FSTCOMFIELD);
		while (cid == null) {
			cid = random.nextInt(9999999) + "";
			setFirstCommunity(uid, cid);
			cid = cluster.getJedis(sPart.shard(uid)).hget(uid,
					CGAXiafan.FSTCOMFIELD);
			// System.err.println("no fst com");
		}
		return cid;
	}

	public void setFirstCommunity(String uid, String cid) {
		cluster.getJedis(sPart.shard(uid))
				.hset(uid, CGAXiafan.FSTCOMFIELD, cid);
		cluster.getJedis(sPart.shard(uid)).sadd(
				Utils.joinStr(uid, CGAXiafan.SETOFCOMMUNITIES), cid);
		ifr.writeln(CGAXiafan.FSTCOMFIELD + "\t" + uid + "\t" + cid);
	}
}
